import React, { useRef, useState } from 'react';
import _ from 'lodash';
import { Button, message, Popconfirm, Tooltip, Input } from 'antd';
import CommonTable from '@/components/CommonTable';
import ConfigDialog from './components/configDialog';
import DebounceWrapper from '@/components/DebounceWrapper';
import { DeleteOutlined, EditOutlined, InfoCircleOutlined, PlusOutlined } from '@ant-design/icons';
import {
  batchDeleteConfigById,
  deleteConfigItemById,
  sysConfigInfo,
} from '@/services/system/configuration';
const DebounceButton = DebounceWrapper(Button);
export default () => {
  const tableRef = useRef(null);
  const [deleteLoading, setDeleteLoading] = useState(false);
  const [deleteLoadingIds, setDeleteLoadingIds] = useState([]);
  const [configFormVisible, setConfigFormVisible] = useState(false);
  const [configFormOptions, setConfigFormOptions] = useState({});
  // 切换loading
  const toggleDeleteLoading = (id, status) => {
    setDeleteLoadingIds((list) => {
      const nextList = [...list];
      if (status) {
        nextList.push(id);
      } else {
        const index = _.indexOf(nextList, id);
        if (index > -1) {
          nextList.splice(index, 1);
        }
      }
      return nextList;
    });
  };
  return (
    <>
      <CommonTable
        ref={tableRef}
        rowKey={'id'}
        indexRender
        rowSelection={{ getCheckboxProps: (data) => ({ disabled: false }) }}
        header={{
          headerTitle: '配置列表',
          headerToolsRender: true,
          headerButtonList: [
            {
              key: 'add',
              type: 'primary',
              label: '新增',
              icon: <PlusOutlined />,
            },
            {
              key: 'delete',
              danger: true,
              type: 'primary',
              label: '批量删除',
              loading: deleteLoading,
              confirmText: '确认批量删除所勾选的配置参数？',
              icon: <DeleteOutlined />,
            },
          ],
          headerButtonClick: async ({ key }) => {
            switch (key) {
              case 'add':
                setConfigFormVisible(true);
                break;
              case 'delete':
                const { refresh, getSelectedList } = tableRef.current;
                if (getSelectedList) {
                  const selectedList = getSelectedList();
                  if (selectedList && selectedList.length) {
                    setDeleteLoading(true);
                    try {
                      await batchDeleteConfigById({ ids: _.map(selectedList, 'id') });
                      refresh && refresh();
                      message.success('用户数据批量删除成功');
                    } catch (e) {
                      console.log('删除失败');
                    }
                    setDeleteLoading(false);
                  } else {
                    message.warning('请至少选择一项数据后再操作');
                  }
                }
                break;
            }
          },
        }}
        request={async (params) => {
          // console.log('入参：', params);
          const { records, total } = await sysConfigInfo(params);
          // console.log(records)
          return { data: records, count: total };
        }}
        search={[
          {
            key: 'configName',
            Component: Input,
            searchType: 'LIKE',
            props: {
              label: '参数名称',
              initialValue: [],
            },
            componentProps: {
              allowClear: true,
              placeholder: '请输入',
            },
          },
        ]}
        columns={[
          { title: '参数名称', dataIndex: 'configName', columnControl: { typeList: 'search' } },
          { title: '参数键名', dataIndex: 'configKey', columnControl: { typeList: 'search' } },
          { title: '参数键值', dataIndex: 'configValue', columnControl: { typeList: 'search' } },
          {
            title: '系统内置',
            dataIndex: 'configType',
            columnControl: {
              typeList: 'filter',
              filterDictType: 'sys_config',
            },
          },
          {
            title: (
              <>
                操作
                <Tooltip placement="top" title={'系统预设用户暂不支持编辑、删除等操作'}>
                  <InfoCircleOutlined className="tooltip-information-handle-icon" />
                </Tooltip>
              </>
            ),
            fixed: 'right',
            dataIndex: 'id',
            width: 220,
            render: (text, data) => {
              const isDefaultConfig = false;
              const deleteLoading = _.includes(deleteLoadingIds, text);
              return (
                <>
                  <DebounceButton
                    type="link"
                    size="small"
                    icon={<EditOutlined />}
                    disabled={deleteLoading || isDefaultConfig}
                    onClick={() => {
                      setConfigFormOptions(data);
                      setConfigFormVisible(true);
                    }}
                  >
                    编辑
                  </DebounceButton>
                  <Popconfirm
                    okText="确定"
                    cancelText="取消"
                    title={'确认删除该配置，删除后不可恢复'}
                    placement="topRight"
                    onConfirm={async () => {
                      toggleDeleteLoading(text, true);
                      try {
                        await deleteConfigItemById({ id: text });
                        const { refresh } = tableRef.current;
                        refresh && refresh();
                        message.success('配置删除成功');
                      } catch (e) {
                        console.log('删除失败');
                      }
                      toggleDeleteLoading(text, false);
                    }}
                  >
                    <DebounceButton
                      danger
                      type="link"
                      size="small"
                      icon={<DeleteOutlined />}
                      loading={deleteLoading}
                      disabled={isDefaultConfig}
                    >
                      删除
                    </DebounceButton>
                  </Popconfirm>
                </>
              );
            },
          },
        ]}
      />
      <ConfigDialog
        visible={configFormVisible}
        options={configFormOptions}
        closeModal={() => {
          setConfigFormOptions({});
          setConfigFormVisible(false);
        }}
        updateList={() => {
          const { refresh } = tableRef.current;
          refresh && refresh();
        }}
      />
    </>
  );
};
